ASP.NET OutputCache - more examples

In the previous chapter, we used to see the output cache instructions to cache our page very easily in this chapter, we will look at other ways to use the output cache. We used differentbirth in the previous example, but you can also vary your cash according to other factors. Here is a short list and some examples.

OutputCache - varybyparam

Please see the previous chapter for more information on the varybyparam parameter. 

OutputCache - varybycontrol 

Varybycontrol does what he says - the cache changes depending on the value of the specified control. For example, you can create a dropdown list with a set of selections, and base the contents of the page based on the selected item. In that case, it will be different according to the value of this control, because the content of the page changes accordingly, it is an example of using different instrument parameters:


<%@ OutputCache duration="10" varybyparam="none" varybycontrol="NameOfControl" %>


OutputCache - varybycustom 

Probably the least easy way to use the output cache system, but on the other hand, perhaps the most flexible, allows you to handle your own variations by setting a custom string, which will vary in output by ASP.NET . To test this, you need to add a global.xx file to your project, right click on your project in the solution project if you do not already have one, and select Add new item. Now select "Global Application Class" and right click in the Global.asax file, you need to override GetVaryByCustomString like this:


public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if(custom == "Browser")
    {
        return context.Request.Browser.Browser;
    }
    return String.Empty;
}

In this case, our caching will be varied based on which browser the user accesses the page with. The markup part should be written like this:


<%@ OutputCache duration="120" varybyparam="None" varybycustom="Browser" %>

Try reaching the page from different browsers You will see that the output now depends on the browser you are using. The browser object comes with a bunch of useful information about the client browser - for example you may have different browsers whether they support CSS, Javascript or something else

OutputCache - varybyheader 

This one allows you to vary the content based on one or more of the headers that browser send. Here is an example:


<%@ OutputCache duration="120" varybyparam="None" varybyheader="Accept-Language" %>

This will vary cache based on the Accept-Language header, which tells the server which languages the user accepts and prefers.